#include <16F628A.h>

#FUSES NOWDT                    //No Watch Dog Timer
#FUSES INTRC_IO                 //Internal RC Osc, no CLKOUT
#FUSES NOPUT                    //No Power Up Timer
#FUSES NOPROTECT                //Code not protected from reading
#FUSES NOBROWNOUT               //No brownout reset
#FUSES NOMCLR                   //Master Clear pin used for I/O
#FUSES NOLVP                    //No low voltage prgming, B3(PIC16) or B5(PIC18) used for I/O
#FUSES NOCPD                    //No EE protection

#use delay(clock=4000000)
#use rs232(baud=9600,parity=N,rcv=PIN_B0,bits=8,stream=RFID)

//char display = 0x01;
char reader = 0x02;
#define RS485_ID reader

#include "rs485_multi.c"

int1 redeOK = FALSE;
//int1 displayOK = FALSE;
int1 hasID= FALSE;

unsigned int8 msgsz;
unsigned char msg[40];

char id[10];
unsigned int8 idsize=0;

void  getRFID() 
{
   char c;
   if(hasID) return;
   c = fgetc(RFID);
   id[idsize] = c;
   if(idsize==0 && c != 0x02) return;
   id[idsize++] = c;
 
   if(idsize==10)
   {
      output_high(pin_a2);
      output_high(pin_a3);
      hasID=true;
   }
}

void getMsg()
{
/*
   0 - start byte($ 0x24)
   1 - packet number
   2 - len
   3 - from
   4 - to
   5 - data (command)
   last - sum
*/

   if(msg[4] == reader)
   {
      if(!redeOK) redeOK=true;
      
      if(msg[5] == 0xFF && msg[3] == 0)
      {
         delay_ms(10);
         rs485_send_raw(msg[6],msg[7]);
      }
      else if(msg[5] == 3 && msg[3] == 0) //resposta positiva
      {
         output_low(pin_a2);
         output_high(pin_a3);
      }
      else if(msg[5] == 4 && msg[3] == 0) //resposta negativa
      {
         output_high(pin_a2);
         output_low(pin_a3);
      }
   }
}

void main()
{
   unsigned int8 i;
   char msgsend[10];

   setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);
   setup_timer_1(T1_INTERNAL|T1_DIV_BY_8);
   setup_timer_2(T2_DISABLED,0,1);
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);
   enable_interrupts(GLOBAL);
   
   redeOK = FALSE;
   //displayOK = FALSE;
   hasID = FALSE;
   idsize=0;
   
   rs485_init();
   
   if(rs485_send_message(0x00, 1, 0x00)) redeOK=true;

   while(true)
   {
      msgsz = rs485_get_message(&(msg[0]));
      if(msgsz>0) getMsg();
      
      if(kbhit(RFID))
         while(kbhit(RFID) && !hasID)
            getRFID();
         
      if(hasID)
      {
         msgsend[0] = 0x02;
         for (i=1;i<10;++i)
            msgsend[i] = id[i];
            
         if(!rs485_send_message(0x00, 9, msgsend))
         {
            output_low(pin_a2);
            output_low(pin_a3);
         }
         hasID=FALSE;
         idsize=0;
      }
   }
}



